package com.mid;

import java.util.*;

/**
 * Created by Lxk on 2019/6/8.
 */

public class Solution451 {

    static class CharCount implements Comparable{

        private char words;

        private int count;

        public CharCount(){}

        public CharCount(char words,int count){
            this.words = words;
            this.count = count;
        }

        @Override
        public int compareTo(Object o) {
            CharCount other = (CharCount) o;
            return other.count-this.count;
        }
    }

    public String frequencySort(String s) {
        if(s==null){
            return null;
        }
        Map<Character,Integer> map = new HashMap<>();
        for(int i = 0;i < s.length(); i++){
            if(map.containsKey(s.charAt(i))){
                map.put(s.charAt(i),map.get(s.charAt(i))+1);
            }else{
                map.put(s.charAt(i),1);
            }
        }
        List<CharCount> list = new ArrayList<>();
        for(Map.Entry<Character,Integer> entry : map.entrySet()){
            list.add(new CharCount(entry.getKey(),entry.getValue()));
        }
        Collections.sort(list);
        StringBuffer sb = new StringBuffer();
        for(CharCount each : list){
            for(int i = 0;i < each.count; i++){
                sb.append(each.words);
            }
        }
        return sb.toString();
    }

}
